﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;
using Newtonsoft.Json;
namespace MVCDemo.Chat
{
    /// <summary>
    /// 消息处理
    /// </summary>
    public class MessageDealWidth
    {
        public static void DealWidth(byte[] recData,WebSocket webSocket)
        {
            try
            {
                string message = Encoding.UTF8.GetString(recData);
                MessageData data = JsonConvert.DeserializeObject<MessageData>(message);
                if (data != null)
                {
                    switch (data.MessageType)
                    {
                        case MessageType.Line:
                            AsyncUserToken userToken = null;
                            //处理连接消息
                            if (ConnectionManager.Connections.ContainsKey(data.SendTokenID))
                            {
                                ConnectionManager.Connections.TryGetValue(data.SendTokenID, out userToken);
                            }
                            else
                            {
                                userToken = new AsyncUserToken();
                                userToken.ConnectSocket = webSocket;
                                userToken.TokenId = data.SendTokenID;
                                userToken.NickName = data.MessageBody;
                                ConnectionManager.Connections.TryAdd(data.SendTokenID, userToken);
                            }
                            if (userToken != null)
                            {
                                //通知所有在线用户
                                foreach (AsyncUserToken token in ConnectionManager.Connections.Values)
                                {
                                    if (token.TokenId != data.SendTokenID&&token.ConnectSocket.State==WebSocketState.Open)
                                    {
                                        MessageData loginMessage = new MessageData();
                                        loginMessage.MessageBody = data.MessageBody;
                                        loginMessage.MessageID = Guid.NewGuid().ToString().Replace("-", "");
                                        loginMessage.MessageType = MessageType.LineNotice;
                                        loginMessage.ReceiveTokenID = data.ReceiveTokenID;
                                        loginMessage.SendTokenID = data.SendTokenID;
                                        byte[] sendLine = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(loginMessage));
                                        var segLine = new ArraySegment<byte>(sendLine, 0, sendLine.Length);
                                        token.ConnectSocket.SendAsync(segLine, WebSocketMessageType.Text, true, CancellationToken.None);
                                    }
                                }
                                //向连接的用户发送在线用户的昵称信息
                                StringBuilder builderNickName = new StringBuilder();
                                foreach (AsyncUserToken token in ConnectionManager.Connections.Values)
                                {
                                    if (token.TokenId != data.SendTokenID && token.ConnectSocket.State == WebSocketState.Open)
                                    {
                                        builderNickName.AppendFormat("{0}|",token.NickName);
                                    }
                                }
                                MessageData nameMessage = new MessageData();
                                nameMessage.MessageBody = builderNickName.ToString().TrimEnd('|');
                                nameMessage.MessageID = Guid.NewGuid().ToString().Replace("-", "");
                                nameMessage.MessageType = MessageType.LineReceipt;
                                nameMessage.ReceiveTokenID = data.ReceiveTokenID;
                                nameMessage.SendTokenID = data.SendTokenID;
                                byte[] sendLogin = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(nameMessage));
                                var segLogin = new ArraySegment<byte>(sendLogin, 0, sendLogin.Length);
                                userToken.ConnectSocket.SendAsync(segLogin, WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                            break;
                        case MessageType.Text:
                            //向加入聊天室的人发送聊天记录
                            foreach (AsyncUserToken token in ConnectionManager.Connections.Values)
                            {
                                if (token.TokenId!=data.SendTokenID && token.ConnectSocket.State == WebSocketState.Open)
                                {
                                    MessageData loginMessage = new MessageData();
                                    loginMessage.MessageBody = data.MessageBody;
                                    loginMessage.MessageID = Guid.NewGuid().ToString().Replace("-", "");
                                    loginMessage.MessageType = MessageType.Text;
                                    loginMessage.ReceiveTokenID = data.ReceiveTokenID;
                                    loginMessage.SendTokenID = data.SendTokenID;
                                    byte[] sendLogin = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(loginMessage));
                                    var segLogin = new ArraySegment<byte>(sendLogin, 0, sendLogin.Length);
                                    token.ConnectSocket.SendAsync(segLogin, WebSocketMessageType.Text, true, CancellationToken.None);
                                }
                            }
                            
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
